package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1. 校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号不合法");
        }

        //2. 校验验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY+phone);
        String code = loginForm.getCode();
        if(cacheCode==null||!cacheCode.equals(code)){
            return Result.fail("验证码不正确");
        }

        //3. 根据手机号查询用户
        User user = query().eq("phone", phone).one();

        //4. 用户不存在,则新创建用户
        if(user==null){
            user=createUserWithPhone(phone);
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);

        //5. 保存用户到redis
        String token = UUID.randomUUID().toString(true);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create().ignoreNullValue().setFieldValueEditor((fieldKey, fieldValue) -> fieldValue.toString()));
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token,userMap);
        stringRedisTemplate.expire(LOGIN_USER_KEY+token,LOGIN_USER_TTL,TimeUnit.SECONDS);

        return Result.ok(token);
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX +RandomUtil.randomString(10));

        save(user);

        return user;
    }

    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 1. 校验手机验证码
        if(RegexUtils.isPhoneInvalid(phone)){
            // 2. 如果失败,则抛出异常
            return Result.fail("手机号码不合法");
        }

        // 3. 如果成功,生成验证码
        String code = RandomUtil.randomNumbers(6);

        // 4. 保存验证码到redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);

        // 5. 发送验证码
        log.info("code="+code);

        // 6. 返回
        return Result.ok();
    }

    @Override
    public Result sign() {
        //1. 获取用户id
        Long userId = UserHolder.getUser().getId();

        //2. 获取当前日期
        LocalDateTime now = LocalDateTime.now();

        //3. 构建key
        String monthSuffix = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String key= USER_SIGN_KEY+userId+":"+monthSuffix;

        //4. 计算日期offset
        int dayOfMonth = now.getDayOfMonth();

        //5. 保存
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);

        return Result.ok();
    }

    @Override
    public Result signCount() {
        //1. 获取用户id
        Long userId = UserHolder.getUser().getId();

        //2. 获取当前日期
        LocalDateTime now = LocalDateTime.now();

        //3. 构建key
        String monthSuffix = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String key= USER_SIGN_KEY+userId+":"+monthSuffix;

        //4. 计算日期offset
        int dayOfMonth = now.getDayOfMonth();

        //5. 获取月初到当天的所有统计结果 setbit key get u29 0
        List<Long> result = stringRedisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );
        if (result==null||result.isEmpty()) {
            return Result.ok(0);
        }
        Long num = result.get(0);

        //6. 循环遍历
        int count=0;
        while(true){
            if((num&1)==0){
                break;
            }else{
                count++;
            }
            num>>>=1;
        }

        return Result.ok(count);
    }
}
